#include "indirectpointerblock.h"


//----------------------------------------------------------------------
// FileHeader::WriteBack
// 	Write the modified contents of the file header back to disk.
//
//	"sector" is the disk sector to contain the file header
//----------------------------------------------------------------------

void
IndirectPointerBlock::WriteBack(int sector)
{
    synchDisk->WriteSector(sector, (char *)this);
}

void
IndirectPointerBlock::FetchFrom(int sector)
{
    synchDisk->ReadSector(sector, (char *)this);
}


void IndirectPointerBlock::PutSector(int sector)
{
	int index = findNextEmptyPointer();
    dataSectors[index] = sector;
}

void
IndirectPointerBlock::Deallocate(BitMap *freeMap)
{
    for (int i = 0; i < NumPointersPerIndirect; i++)
	{
		if(dataSectors[i] == 0)
			continue;
        ASSERT(freeMap->Test((int) dataSectors[i]));  // ought to be marked!
        freeMap->Clear((int) dataSectors[i]);
    }
	clear();
}

int
IndirectPointerBlock::ByteToSector(int offset)
{
    return(dataSectors[offset / SectorSize]);
}

// Write zeros across all pointers to show that they are unsused / empty
void IndirectPointerBlock::clear()
{
	for(int i=0; i<NumPointersPerIndirect; i++)
	{
		dataSectors[i] = 0;
	}

}

int IndirectPointerBlock::findNextEmptyPointer()
{
	for(int i=0; i<NumPointersPerIndirect; i++)
	{
		if(dataSectors[i] == 0)
			return i;
	}
	return -1;
}

int IndirectPointerBlock::getNumFreePointers()
{
	int counter = 0;
	for(int i=0; i<NumPointersPerIndirect; i++)
	{
		if(dataSectors[i] == 0)
			counter++;
	}
	return counter;
}
























